#!/user/local/bin/python

# -*-encoding:utf-8 -*-

import sys
freq_dict = {};
def loadFrequencyDict(frequencyFile):
    for line in open(frequencyFile, 'r'):
        li = line.strip().split('\t');
        freq_dict[li[1]] = int(li[0]);

def process(labeled, sort_labeled):
    labeled = open(labeled, 'r');
    sort_labeled = open(sort_labeled, 'w');

    for line in labeled:
        line = line.strip();
        li = line.split('|');
        queryString = li [0];
        appList = [];
        for i in range(1, len(li)):
            appLi = li[i].split(':');
            appList.append((int(appLi[2]),appLi[1]));
        appList.sort();
        s = '%d|%s|%s\n' % (freq_dict.get(queryString.lower(),0), queryString, '|'.join(['%d:%s:%d' %(pos, item[1], item[0] ) for pos, item in enumerate(appList)]));
        sort_labeled.write(s);
    labeled.close();
    sort_labeled.close();

if __name__ == '__main__':
    labeled = sys.argv[1];
    sort_labeled = sys.argv[2];
    frequencyFile = sys.argv[3];
    loadFrequencyDict(frequencyFile);

    process(labeled, sort_labeled); 
    
